import Vue from "vue";
import {security_const} from "./constant";
import {routeAuthHandler} from "./common";
import _ from 'lodash/core'

let observe = Vue.observable({
  oauthToken: JSON.parse(sessionStorage.getItem(security_const.auth_tag) || "{}"),
  permission: JSON.parse(sessionStorage.getItem(security_const.permission) || "[]"),
  authCode: JSON.parse(sessionStorage.getItem(security_const.auth_code) || "[]"),
  authMenu: JSON.parse(sessionStorage.getItem(security_const.auth_menu) || "[]"),
  authUser:JSON.parse(sessionStorage.getItem(security_const.auth_menu) || "{}"),
});
let mutation = {
  logoutClean(){
    this.changeOauthToken({})
    this.changeAuthCode([])
    this.changePermission([])
    this.changeAuthMenu([])
    this.changeAuthUser([])
  },
  changeOauthToken(oauthToken) {
    try {
      if (!_.isEmpty(oauthToken)) {
        oauthToken[security_const.expired_at] = Date.now() + oauthToken.expires_in * 1000
        sessionStorage.setItem(security_const.auth_tag, JSON.stringify(oauthToken))
      } else {
        sessionStorage.removeItem(security_const.auth_tag)
      }
      observe.oauthToken = oauthToken
    }catch (e) {
      console.error(e)
    }
  },
  changePermission(permission) {
    try{
      observe.permission = permission
      if (!_.isEmpty(permission)) {
        sessionStorage.setItem(security_const.permission, JSON.stringify(permission))
        let authCode=permission.map(entry => entry.code)
        this.changeAuthCode(authCode)
        let authMenuRouter = routeAuthHandler()
        this.changeAuthMenu(authMenuRouter)

      } else {
        sessionStorage.removeItem(security_const.permission)
        this.changeAuthCode([])
        this.changeAuthMenu([])
      }
    }catch (e) {
      console.error(e)
    }

  },
  changeAuthUser(authUser) {
    try {
      observe.authUser = authUser
      if (!_.isEmpty(authUser)) {
        sessionStorage.setItem(security_const.auth_user, JSON.stringify(authUser))
      } else {
        sessionStorage.removeItem(security_const.auth_user)
      }
    }catch (e) {
      console.error(e)
    }
  },
  changeAuthCode(authCode) {
    try {
      observe.authCode = authCode
      if (!_.isEmpty(authCode)) {
        sessionStorage.setItem(security_const.auth_code, JSON.stringify(authCode))
      } else {
        sessionStorage.removeItem(security_const.auth_code)
      }
    }catch (e) {
      console.error(e)
    }
  },
  changeAuthMenu(authMenu) {
    try{
    observe.authMenu = authMenu
      if (!_.isEmpty(authMenu)) {
        sessionStorage.setItem(security_const.auth_menu, JSON.stringify(authMenu))
      } else {
        sessionStorage.removeItem(security_const.auth_menu)
      }
    }catch (e) {
      console.error(e)
    }
  }

}

export let securityStore = {
  observe, mutation
}